<!--
 * @Author: yanjikun
 * @Date: 2022-05-13 11:13:36
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-24 15:44:45
 * @Description: file content
-->
<template>
  <Form :model="formState" name="loginByPassword" @Finish="handleSubmit">
    <Form.Item name="login" :rules="[{ required: true, message: '请输入用户名！' }]">
      <Input v-model:value="formState.login" size="large" placeholder="请输入用户名">
        <template #prefix>
          <UserOutlined />
        </template>
      </Input>
    </Form.Item>
    <Form.Item name="password" :rules="[{ required: true, message: '请输入密码！' }]">
      <Input.Password v-model:value="formState.password" size="large" placeholder="请输入密码">
        <template #prefix>
          <LockOutlined class="site-form-item-icon" />
        </template>
      </Input.Password>
    </Form.Item>
    <Form.Item name="remember" :no-style="true">
      <Checkbox v-model:checked="formState.remember" style="margin-bottom: 8px">记住我</Checkbox>
    </Form.Item>
    <Form.Item>
      <Button type="primary" size="large" html-type="submit" class="w-full" :loading="loading">
        登录
      </Button>
    </Form.Item>
  </Form>
</template>

<script setup lang="ts">
  import { Form, Input, Checkbox, Button, notification } from 'ant-design-vue'
  import { reactive, ref } from 'vue'
  import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
  import { useUserStore } from '@/store/modules/user'
  import { useRoute, useRouter } from 'vue-router'
  import { LOGIN_TO_DEFAULT_PATH } from '@/settings/systemSetting'
  import { storage } from '@/utils/Storage'
  import { LOGIN_FORM_MODEL } from '@/enums/cacheEnums'
  interface FormState {
    login: string
    password: string
    remember: boolean
  }
  const useUser = useUserStore()
  const router = useRouter()
  const route = useRoute()
  const formState = reactive<FormState>(
    storage.get(LOGIN_FORM_MODEL, {
      login: '',
      password: '',
      remember: true,
    }),
  )
  const loading = ref(false)
  const handleSubmit = async (values: FormState) => {
    loading.value = true
    try {
      const params: API.LoginParams = {
        ...values,
        type: 1,
      }
      await useUser.login(params).finally(() => {
        loading.value = false
      })
      handleRememberPassword()
      notification.success({
        message: '登录成功！',
        description: `欢迎回来：${useUser.info?.username}`,
      })
      setTimeout(() => router.replace((route.query.redirect as string) ?? LOGIN_TO_DEFAULT_PATH))
    } catch (error) {
      console.log(error)
    }
  }
  const handleRememberPassword = () => {
    formState.remember && storage.set(LOGIN_FORM_MODEL, formState)
  }
</script>

<style scoped lang="less"></style>
